"""
Case Type   : 系统内部使用工具
Case Name   : 指定一个物理复制槽，将日志目录包含到备份中、将检查点在一段时间
             内展开，指定-S、--backup-pg-log、-C选项进行备份
Create At   : 2021/11/16
Owner       : zopentestcase005
Description :
    1.创建备份目录
    2.创建物理复制槽
    3.进行初始化
    4.添加实例
    5.执行备份
    6.清理环境
Expect      :
    1.创建成功
    2.创建成功
    3.初始化成功
    4.添加成功
    5.备份成功
    6.清理环境完成
History     :
    modified by opentestcase010 at 2022/11/21:优化查询信息，适配3.1.0新版本
    modified by opentestcase010 at 2023-08-7:添加等待时间
    modified by l1azzzy at 2024/12/5:优化提示信息，以及逻辑，适配7.0.0-RC1版本
"""

import os
import unittest
import time

from testcase.utils.CommonSH import CommonSH
from testcase.utils.Constant import Constant
from testcase.utils.Logger import Logger
from yat.test import Node
from yat.test import macro


class SystemInternalTools(unittest.TestCase):
    def setUp(self):
        self.log = Logger()
        self.log.info('--Opengauss_Function_Tools_Gs_Probackup_Case0048start-')
        self.constant = Constant()
        self.Primary_Node = Node('PrimaryDbUser')
        self.pri_sh = CommonSH('PrimaryDbUser')
        self.gs_probackup_path = os.path.join(macro.DB_INSTANCE_PATH,
                                              'gs_probackup_testdir0048')
        self.slot_name = "slot_gs_probackup_case0048"

    def test_system_internal_tools(self):
        text = '--step1:创建备份目录;expect:创建成功----'
        self.log.info(text)
        mkdir_cmd = f'''if [ ! -d "{self.gs_probackup_path}" ]
                        then
                            mkdir -p {self.gs_probackup_path}
                        fi'''
        primary_result = self.Primary_Node.sh(mkdir_cmd).result()
        self.log.info(primary_result)
        self.assertEqual(primary_result, '', '执行失败:' + text)

        text = '--step2:创建物理复制槽;expect:创建成功--'
        self.log.info(text)
        sql_cmd = f"select * from pg_create_physical_replication_slot" \
                  f"('{self.slot_name}', true);" \
                  f"select slot_name from pg_replication_slots;"
        sql_res = self.pri_sh.execut_db_sql(sql_cmd)
        self.log.info(sql_res)
        self.assertEqual(f"{self.slot_name}",
                         sql_res.splitlines()[-2].strip(),  '执行失败:' + text)

        text = '--step3:进行初始化;expect:初始化成功---'
        self.log.info(text)
        init_cmd = f"source {macro.DB_ENV_PATH};" \
                   f"gs_probackup init -B {self.gs_probackup_path};"
        self.log.info(init_cmd)
        init_msg = self.Primary_Node.sh(init_cmd).result()
        self.log.info(init_msg)
        self.assertIn(self.constant.init_success, init_msg,
                      '执行失败:' + text)

        text = '--step4:添加实例;expect:添加成功----'
        self.log.info(text)
        init_cmd = f"source {macro.DB_ENV_PATH};" \
                   f"gs_probackup add-instance " \
                   f"-B {self.gs_probackup_path} " \
                   f"-D {macro.DB_INSTANCE_PATH} " \
                   f"--instance=test_0048 "
        self.log.info(init_cmd)
        init_msg = self.Primary_Node.sh(init_cmd).result()
        time.sleep(2)
        self.log.info(init_msg)
        self.assertIn("'test_0048' " + self.constant.init_success, init_msg,
                      '执行失败:' + text)

        text = '---step5:执行备份;expect:备份成功---'
        self.log.info(text)
        backup_cmd = f"source {macro.DB_ENV_PATH};" \
                     f"gs_probackup backup -B {self.gs_probackup_path} " \
                     f"-b full  --stream  --instance=test_0048  " \
                     f"--no-validate  -p {self.Primary_Node.db_port} " \
                     f"-d postgres -S {self.slot_name} --backup-pg-log -C"
        self.log.info(backup_cmd)
        backup_msg = self.Primary_Node.sh(backup_cmd).result()
        self.log.info(backup_msg)
        self.assertIn('completed', backup_msg, '执行失败:' + text)

    def tearDown(self):
        text = '---step6:清理环境;清理环境完成---'
        self.log.info(text)
        clear_cmd = f'rm -rf {self.gs_probackup_path}'
        self.log.info(clear_cmd)
        clear_msg = self.Primary_Node.sh(clear_cmd).result()
        self.log.info(clear_msg)
        sql_cmd = f"select * from pg_drop_replication_slot" \
                  f"('{self.slot_name}');"
        self.log.info(sql_cmd)
        sql_res = self.pri_sh.execut_db_sql(sql_cmd)
        self.log.info(sql_res)
        msg = sql_res.splitlines()
        for n in msg[::-1]:
            if n == "" or n.startswith("WARNING"):
                msg.remove(n)
        self.log.info(msg)
        self.assertEqual('', msg[2].strip(), '执行失败:' + text)
        self.log.info('-Opengauss_Function_Tools_Gs_Probackup_Case0048finish-')
